//
//  MessageSettingVC.m
//  AILock
//
//  Created by 谭亚明 on 2020/7/9.
//  Copyright © 2020 tym. All rights reserved.
//

#import "LockDeployVC.h"
#import "UserModel.h"
#import "ShowAlertView.h"
#import "EquipmentModel.h"
#import "OperationView.h"
#import "LockDeployCell.h"
#import "UIButton+ImageTitleSpacing.h"
#import "BRDatePickerView.h"
#import "UserModel.h"
#import "FamilyModel.h"
#import "UserTool.h"
#import "FamilyModel.h"
#import "MessageSettingCell.h"
#import "Sizes.h"
#import "FamilyService.h"
#import "GroupShadowTableView.h"
#import "FamilyModel.h"
#import "EquipmentService.h"
@interface LockDeployVC ()<GroupShadowTableViewDelegate, GroupShadowTableViewDataSource>

//设备配置详情
@property(nonatomic,strong) Equipmentconfig *config;

@property (nonatomic, strong) GroupShadowTableView *tableView;
@property(nonatomic,strong) EquipmentModel *equipModel;
@property(nonatomic) NSMutableArray *dataArray;

@property(nonatomic,strong) NSMutableArray *sysDicArray;
@property(nonatomic,strong) EquipmentService *services;

@property(nonatomic,strong) FamilyService *familyServices;
@end

@implementation LockDeployVC

-(instancetype)initWithModel:(EquipmentModel*)equipModel{
    self = [super init];
    if (self) {
        self.equipModel = equipModel;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self addBackBtnFunc];
    [self addTitle:@"门锁配置"];
    [self setTable];
    
    
    
    _dataArray = [[NSMutableArray alloc] init];
    _sysDicArray = [[NSMutableArray alloc] init];
    
    [self getSysdictWithDictType];
    //[self getEquipmentOpenCloseStatus];
    [self getEquipmentConfigInfo];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getEquipmentConfigInfo) name:@"updateEquipmentConfigInfo" object:nil];

}

-(void)updateDataArray{
    if(!_config.openInfoPush){
        return;
    }
    if([_config.openDoorParam isEqualToString:@"0A"]){
        _config.openDoorParam = @"10";
    }
    [_dataArray removeAllObjects];
    
    [_dataArray addObjectsFromArray:@[
        @[@{@"title":@"通道功能",
            @"content":@"",@"isOpen":@([_config.channelOpenDoorWay integerValue])},
          @{@"title":@"双重验证",
            @"content":@"用户必须使用指纹，卡或密码中任意两项验证通过后，才可开锁",@"isOpen":@([_config.doubleOpenDoorWay integerValue])}],
        @[@{@"title":@"开门信息",
            @"content":@"",@"isOpen":@([_config.openInfoPush integerValue])},@{@"title":@"报警信息",
                                                                               @"content":@"",@"isOpen":@([_config.alarmInfoPush integerValue])}],
//        @[@{@"title":@"远程开关门",
//            @"content":@"",@"isOpen":@([_config.remoteOpendoorAuth integerValue])}],
        @[@{@"title":@"开锁时间",
            @"content":[_config.openDoorParam stringByAppendingString:@"秒"],@"isOpen":@(3)}]]];
}

-(EquipmentService*)services{
    if (_services == nil) {
        _services = [[EquipmentService alloc] init];
    }
    return _services;
}

-(FamilyService*)familyServices{
    if (_familyServices == nil) {
        _familyServices = [[FamilyService alloc] init];
    }
    return _familyServices;
}

//获取系统语言配置
-(void)getSysdictWithDictType{
    TYMWeak(self);
    [self.services getEquipmentSysDictdictType:@"LOCK_PARAMETER_TYPE" completion:^(LMJBaseResponse * _Nonnull resp, NSArray<EquSubSysDict *> * _Nonnull sysArray) {
        if(weakself.sysDicArray){
            [weakself.sysDicArray removeAllObjects];
        }
        [weakself.sysDicArray addObjectsFromArray:sysArray];
        [weakself.tableView reloadData];
    }];
}

//获取开关锁状态
-(void)getEquipmentOpenCloseStatus{
    
    [self.services getEquipmentequipmentId:_equipModel.equipmentId completion:^(LMJBaseResponse * _Nonnull resp, EquipmentModel * _Nonnull equipment) {
        
    }];
}

-(void)getEquipmentConfigInfo{
    TYMWeak(self);
    [self.services getEquipmentconfiginfo:_equipModel.equipmentId completion:^(NSError * _Nonnull error, Equipmentconfig * _Nonnull equipmentConfig) {
        weakself.config = equipmentConfig;
        [weakself updateDataArray];
        [weakself.tableView reloadData];
    }];
}

- (void)setTable {
    self.tableView = [[GroupShadowTableView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight-NavigateonHeight-SafeBottomMargin) style:UITableViewStyleGrouped];
    self.tableView.headTitles = @[@"开门方式",@"信息推送",@"开锁参数",@"门锁语音"];
    self.tableView.isShowArray = @[@(1),@(1),@(1),@(1)];
    self.tableView.groupShadowDelegate = self;
    self.tableView.groupShadowDataSource = self;
    self.tableView.backgroundColor = viewBGColor;
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 0.01)];
    self.tableView.sectionFooterHeight = 0;
    _tableView.showSeparator = NO;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
}

-(void)switchActionWithSection:(NSIndexPath*)indexPath isOpen:(BOOL)open{
    
    TYMWeak(self);
    if (indexPath.section == 0) { //开门方式
        [self.services getOpendoorwayEuipmentId:_equipModel.equipmentId action:@"01" parameteType:indexPath.row?@"01":@"00" parmeteValue:open?@"01":@"00" completion:^(LMJBaseResponse * _Nonnull respons) {
            if (respons.message) {
                [ShowAlertView showAlertViewTitle:@"提示" message:respons.message actionBtnTitle:@"确定"
                                       hiddenCancel:NO
                                       completion:^(NSInteger actionType) {
                    if(actionType){
                        if (respons.code == 2001 || respons.code == 29) {
                            [weakself getVerifyAdminroleSection:indexPath isOpen:open];
                        }
                    }
                }];
            }else{
                [WHToast showMessage:@"设置成功" duration:2 finishHandler:nil];
                if (indexPath.row) {
                    weakself.config.doubleOpenDoorWay = open?@"01":@"00";
                }else{
                    weakself.config.channelOpenDoorWay = open?@"01":@"00";
                }
            }
            [weakself updateDataArray];
            [weakself.tableView reloadData];
        }];
        
    }else if (indexPath.section == 1) { //信息推送
        [self.services getInformationpushEuipmentId:_equipModel.equipmentId action:@"01" parameteType:indexPath.row?@"02":@"01" parmeteValue:open?@"01":@"00" completion:^(LMJBaseResponse * _Nonnull respons) {
            if (respons.message) {
                [ShowAlertView showAlertViewTitle:@"提示" message:respons.message actionBtnTitle:@"确定"
                                       hiddenCancel:NO
                                       completion:^(NSInteger actionType) {
                    if(actionType){
                        if (respons.code == 2001|| respons.code == 29) {
                            [weakself getVerifyAdminroleSection:indexPath isOpen:open];
                        }
                    }
                }];
            }else{
                [WHToast showMessage:@"设置成功" duration:2 finishHandler:nil];
                if (indexPath.row) {
                    weakself.config.alarmInfoPush = open?@"01":@"00";
                }else{
                    weakself.config.openInfoPush = open?@"01":@"00";
                }
            }
            [weakself updateDataArray];
            [weakself.tableView reloadData];
        }];
    }else if (indexPath.section == 2) { //远程开关门
//        [self.services getRemoteaccesspermissionEuipmentId:_equipModel.equipmentId action:@"01" parmeteValue:open?@"01":@"00" completion:^(LMJBaseResponse * _Nonnull respons) {
//
//            if (respons.message) {
//                [ShowAlertView showAlertViewTitle:@"提示" message:respons.message actionBtnTitle:@"确定"
//                                       hiddenCancel:NO
//                                       completion:^(NSInteger actionType) {
//                    if(actionType){
//                        if (respons.code == 2001|| respons.code == 29) {
//                            [weakself getVerifyAdminroleSection:indexPath isOpen:open];
//                        }
//                    }
//                }];
//            }else{
//                [WHToast showMessage:@"设置成功" duration:2 finishHandler:nil];
//                weakself.config.remoteOpendoorAuth = open?@"01":@"00";
//            }
//            [weakself updateDataArray];
//            [weakself.tableView reloadData];
//        }];
    }
}

//验证管理员
-(void)getVerifyAdminroleSection:(NSIndexPath*)indexPath isOpen:(BOOL)open{
    TYMWeak(self);
    [self.services getVerifyadminroleEpumentId:self.equipModel.equipmentId completion:^(LMJBaseResponse * _Nonnull respons) {
        if (respons.code == 0) {
            [weakself switchActionWithSection:indexPath isOpen:open];
        }else{
            [WHToast showMessage:respons.message duration:2 finishHandler:nil];
        }
    }];
}

//验证管理员
-(void)getVerifyAdminroleSection:(NSIndexPath*)indexPath index:(NSInteger)index{
    TYMWeak(self);
    [self.services getVerifyadminroleEpumentId:self.equipModel.equipmentId completion:^(LMJBaseResponse * _Nonnull respons) {
        if (respons.code == 0) {
            [weakself setDeployVCWithSection:indexPath WithIndex:index];
        }else{
            [WHToast showMessage:respons.message duration:2 finishHandler:nil];
        }
    }];
}

#pragma mark delegate datasource
- (NSInteger)numberOfSectionsInGroupShadowTableView:(GroupShadowTableView *)tableView {
    return 4;
}

- (NSInteger)groupShadowTableView:(GroupShadowTableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section<3) {
        if (_dataArray.count) {
            NSArray *array = _dataArray[section];
            return array.count;
        }
    }else{
        return self.sysDicArray.count;
    }
    return 0;
}

- (CGFloat)groupShadowTableView:(GroupShadowTableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if(indexPath.section == 0 && indexPath.row == 1){
        return [MessageSettingCell cellForHeight] + 15;
    }
    return [MessageSettingCell cellForHeight];
}

- (UITableViewCell *)groupShadowTableView:(GroupShadowTableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    LockDeployCell  *cell = [tableView dequeueReusableCellWithIdentifier:[MessageSettingCell identifier]];
    if (!cell) {
        cell = [[LockDeployCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:[MessageSettingCell identifier]];
    }
    
    if (indexPath.section < 3) {
        cell.dataDic = self.dataArray[indexPath.section][indexPath.row];
    }else{
        cell.config = self.config;
        cell.sysDict = self.sysDicArray[indexPath.row];
    }
    
    cell.changeSwitchBlock = ^(BOOL switchOn) {
        
        [self switchActionWithSection:indexPath isOpen:switchOn];
    };
    return cell;
}


-(void)groupShadowTableView:(GroupShadowTableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    TYMWeak(self);
    //家庭成员返回
    if ([UserTool getCurrentFamily].familyRole == 2) {
        return;
    }
    
    if (indexPath.section == 2) {
        NSArray *array = @[@"2秒",@"3秒",@"4秒",@"5秒",@"6秒",@"7秒",@"8秒",@"9秒",@"10秒"];
        OperationView *pop = [[OperationView alloc]initWithFrame:self.view.frame];
        pop.data = array;
        pop.blockCallBackIndex = ^(NSInteger index) {
            [weakself setDeployVCWithSection:indexPath WithIndex:index];
        };
        [pop viewShow];
    }else if (indexPath.section == 3) {
        
        EquSubSysDict *subSys =  self.sysDicArray[indexPath.row];
        NSArray *equArray = subSys.subSysDictList;
        NSMutableArray *titArray = [[NSMutableArray alloc] init];
        for (EquSubSysDict *dict in equArray){
            [titArray addObject:dict.dictName];
        }
        OperationView *pop = [[OperationView alloc]initWithFrame:self.view.frame];
        pop.data = titArray;
        [pop viewShow];
        pop.blockCallBackIndex = ^(NSInteger index) {
            [self setDeployVCWithSection:indexPath WithIndex:index];
        };
    }
}

-(void)setDeployVCWithSection:(NSIndexPath*)indexPath WithIndex:(NSInteger)index{
    
    if (indexPath.section == 3) {
        NSArray *array = @[@"02",@"03",@"04",@"05",@"06",@"07",@"08",@"09",@"0A"];
        [self.services getOpenlockparameterEuipmentId:_equipModel.equipmentId action:@"01" parameteType:@"01" parmeteValue:array[index] completion:^(LMJBaseResponse * _Nonnull respons) {
            if (respons.code != 0) {
                
                [ShowAlertView showAlertViewTitle:@"提示" message:respons.message actionBtnTitle:@"确定"
                                       hiddenCancel:NO
                                       completion:^(NSInteger actionType) {
                    if(actionType){
                        if (respons.code == 2001|| respons.code == 29) {
                            [self getVerifyAdminroleSection:indexPath index:index];
                        }
                    }
                }];
            }else{
                [WHToast showMessage:@"设置成功" duration:2 finishHandler:nil];
                _config.openDoorParam = array[index];
                [self updateDataArray];
                [self.tableView reloadData];
            }
        }];
    }else if(indexPath.section == 4){
        NSString *parameterType;
        NSString *parameterValue;
        if (indexPath.row == 0) {
            parameterType = @"01";
        }else if(indexPath.row == 1){
            parameterType = @"02";
        }else if(indexPath.row == 2){
            parameterType = @"03";
        }else if(indexPath.row == 3){
            parameterType = @"04";
        }
        
        if (index == 0) {
            parameterValue = @"00";
        }else if(index == 1){
            parameterValue = @"01";
        }else if(index == 2){
            parameterValue = @"02";
        }else if(index == 3){
            parameterValue = @"03";
        }
        
        [self.services getWarningtonemanagerEuipmentId:_equipModel.equipmentId action:@"01" parameteType:parameterType parmeteValue:parameterValue completion:^(LMJBaseResponse * _Nonnull respons) {
            if (respons.code != 0) {
                [ShowAlertView showAlertViewTitle:@"提示" message:respons.message actionBtnTitle:@"确定"
                                       hiddenCancel:NO
                                       completion:^(NSInteger actionType) {
                    if(actionType){
                        if (respons.code == 2001|| respons.code == 29) {
                            [self getVerifyAdminroleSection:indexPath index:index];
                        }
                    }
                }];
            }else{
                [WHToast showMessage:@"设置成功" duration:2 finishHandler:nil];
                [self getEquipmentConfigInfo];
            }
        }];
    }
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
